<template>
  <div class="userBox">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- @blur="getSearchUsers" -->
    <!-- 用户列表主体 -->
    <el-card class="box-card">
      <!-- 搜索框和添加用户按钮 -->
      <el-row type="flex">
        <el-col :span="8">
          <div class="grid-content bg-purple title" style="text-align: left">
            <el-input
              clearable
              placeholder="请输入内容"
              v-model.trim="params.query"
              class="input-with-select"
              @clear="getSearchUsers"
              @keydown.native.enter="getSearchUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getSearchUsers"
              ></el-button>
            </el-input>
          </div>
        </el-col>

        <el-col :span="16">
          <el-row type="flex">
            <el-col :span="2"></el-col>
            <el-col :span="20">
              <el-button type="primary" @click="dialogFormVisible = true"
                >添加用户</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!-- 用户列表-->
      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column type="index" label="#" width="50"> </el-table-column>

        <el-table-column prop="username" label="用户" align="center">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" align="center">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
        </el-table-column>
        <!-- prop="mg_state" -->
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              icon="el-icon-delete"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                size="mini"
                type="warning"
                @click="allocatedLimits(scope.$index, scope.row)"
                icon="el-icon-s-tools"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 8]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage"
    >
    </el-pagination>
    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
      <el-form :model="editForm" ref="form" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="editForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限弹框 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleLimits">
      <el-form :model="limitsForm">
        <el-form-item label="当前的用户" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="当前的角色" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.role_name }}</el-tag>
        </el-form-item>
        <el-form-item
          label="分配新角色:
    "
          :label-width="formLabelWidth"
        >
          <el-select v-model="roleValue" placeholder="请选择">
            <el-option
              v-for="item in rolesUsers"
              :key="item.value"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleLimits = false">取 消</el-button>
        <el-button type="primary" @click="setUsersRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  getChangeUserState,
  getAddUsers,
  getDeleteUsers,
  getQueryUsersById,
  getEditUsers,
  getUsersRole,
  getRoles,
} from "../../api/index";

export default {
  data() {
    // 给mobile单独设置正则
    var validateMobile = (rule, value, callback) => {
      let regMobile = /^[1]([3,9])[0-9]{9}$/;
      if (!regMobile.test(value)) {
        callback(new Error("手机输入不规范"));
      } else {
        callback();
      }
    };

    return {
      tableData: [],
      totalpage: 0, //总页数
      params: {
        query: "",
        pagenum: 1,
        pagesize: 5, //页面条数
      },
      //分页
      // 定义弹框数据
      dialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "200px",
      // 验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
        email: [{ message: "请输入邮箱", trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
      // 编辑用户数据定义
      editdialogFormVisible: false,
      //  编辑弹框列表
      editForm: {
        username: "",
        password: "123456",
        email: "",
        mobile: "",
      },
      // 定义分配权限数据
      dialogFormVisibleLimits: false,
      limitsForm: {
        username: "",
        role_name: "",
      },
      // 用户角色初始处理
      rolesUsers: [],
      // 定义角色的id值
      roleValue: "",
    };
  },
  // users:[]
  // pagenum: 1
  // total: 3
  created() {
    this.getUsersList();
  },
  methods: {
    //初始化获取用户列表
    async getUsersList() {
      let {
        data: { users, pagenum, total },
      } = await getUsers(this.params);

      this.tableData = users;
      this.params.pagenum = pagenum;
      this.totalpage = total;
    },
    //分页功能
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.params.pagenum = val;
      this.getUsersList();
    },

    //搜索功能
    getSearchUsers() {
      this.getUsersList();
    },
    // 改变用户状态
    async changeUserState(data) {
      // console.log(data);
      // console.log({id:data.id,type:data.mg_state});
      let res = await getChangeUserState({ id: data.id, type: data.mg_state });
      // console.log(res);

      let {
        meta: { msg, status },
      } = res;
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        // 更改状态后刷新页面
        this.getUsersList();
      }
    },
    // 添加用户
    async addUsers() {
      //1 表单的验证
      //2 验证通过后发送请求
      //3 发送请求成功后关闭弹框 重新刷新页面
      // 表单验证成功的条件
      let success = await this.$refs["form"].validate().catch(() => {});
      // console.log(success);
      //如果表单验证不成功 就返回false
      if (!success) return false;
      // 表单验证通过之后发送请求
      let {
        meta: { status },
      } = await getAddUsers(this.form);
      //  console.log(status)
      // 对应接口请求成功返回的状态码201
      if (status == 201) {
        // 显示提示信息
        this.$message.success("添加用户成功");
        // 关闭弹框
        this.dialogFormVisible = false;
        //重新刷新页面
        this.getUsersList();
      }
    },

    // 删除用户
    //scope.$index 当前页面行的下标，
    // scope.row  当前页面这一整行的所有数据
    async handleDelete(index, item) {
      // console.log(index);
      // console.log(item);
      // 1.判断是否删除，是就删除，点击取消删除就什么也不做、
      // 2.如果真的删除 发送请求判断回来的数据 请求成功后 执行删除
      let res = await this.$confirm("此次操作将永久删除，是否继续", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});

      if (res != "confirm") return this.$message.info("取消删除");
      let {
        meta: { status, msg },
      } = await getDeleteUsers({ id: item.id });
      console.log(res);
      if (status == 200) {
        this.$message.success("删除成功");
        this.getUsersList();
      } else {
        this.$message.error("删除失败");
      }
    },
    // 编辑用户
    // 1.点击弹出编辑对话框 2.把点击的当前这一项数据展示在对话框的input中(通过id)
    // 然后从后台查询对应的一条数据
    // 3.修改对应的数据修改后进行 数据的编辑请求 ， 成功关闭对话框并且重新刷新页面
    async handleEdit(index, item) {
      // 1.根据id发送请求

      let res = await getQueryUsersById({ id: item.id });
      // console.log(res);
      let {
        data,
        meta: { status },
      } = res;
      // console.log(res)
      if (status != 200) return this.$message.info("查询失败了");
      this.editForm = data;
      // console.log(this.editForm)
      this.editdialogFormVisible = true;
      this.getUsersList();
    },
    // 真正的修改完数据后进行数据编辑
    async editUsers() {
      let {
        meta: { status },
      } = await getEditUsers(this.editForm);
      if (status != 200) return this.$message.info("编辑失败了");
      this.$message.success("编辑成功");
      this.editdialogFormVisible = false;
      this.getUsersList();
    },
    // 分配权限
    // 获取角色列表

    async allocatedLimits(index, item) {
      let { data: rolesList } = await getRoles();
      //  console.log(rolesList)
      // 老师的高级方法
      let newArr = rolesList.reduce((preVal, currentItem) => {
        return [
          ...preVal,
          { id: currentItem.id, roleName: currentItem.roleName },
        ];
      }, []);
      console.log(newArr);
      this.rolesUsers = newArr; //将获取到的下拉框数据传给roleUsers
      // console.log(item)
      // 1.打开弹框
      this.dialogFormVisibleLimits = true;
      // 2.对应的当前用用户名和角色
      this.limitsForm.username = item.username;
      this.limitsForm.role_name = item.role_name;
      this.limitsForm.id = item.id;
    },

    // 3.点击下拉框 发送请求 拿到数据渲染下拉框的数据
    //  获取用户级的分配角色 id this.roleValue
    async setUsersRoles(item) {
      let res = await getUsersRole({
        id: this.limitsForm.id,
        rid: this.roleValue,
      });
      let {
        meta: { status },
      } = res;
      if (status != 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
      this.getUsersList();
      this.dialogFormVisibleLimits = false;
    },
    // 4.真正的点击确认按钮 分配好角色后 关闭弹框，刷新页面
  },
};
</script>

<style scoped>
.box-card {
  width: 900px;
}
.userBox {
  padding-left: 20px;
}

.el-table {
  margin-top: 20px;
}
.el-breadcrumb {
  background-color: #fff;
  padding-left: 20px;
}
.el-pagination {
  margin: 20px auto;
  text-align: center;
}
.el-dialog__body {
  padding: 30px 86px 21px 4px;
}
</style>
